<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ collapsed: sidebarCollapsedState }">
      <!-- Logo区域 -->
      <div class="sidebar-header">
        <div class="logo">
          <div class="logo-icon">
            <el-icon><Setting /></el-icon>
          </div>
          <span v-if="!sidebarCollapsedState" class="logo-text">Admin</span>
        </div>
      </div>
      
      <!-- 菜单区域 -->
      <nav class="sidebar-nav">
        <el-menu
          :default-active="getCurrentMenuCode()"
          :collapse="sidebarCollapsedState"
          background-color="transparent"
          text-color="#71717a"
          active-text-color="#18181b"
          unique-opened
          class="nav-menu"
        >
          <DynamicMenu 
            :menu-data="menuRoutes" 
            @menu-click="handleMenuClick"
          />
        </el-menu>
      </nav>
    </aside>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <header class="header">
        <div class="header-left">
          <el-button
            class="sidebar-toggle"
            text
            @click="toggleSidebar"
          >
            <el-icon :size="18">
              <Menu />
            </el-icon>
          </el-button>
          
          <!-- 面包屑导航 -->
          <div class="breadcrumb-nav" v-if="showBreadcrumb">
            <Breadcrumb />
          </div>
        </div>
        
        <div class="header-right">
          <!-- 搜索框 -->
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索..."
              :prefix-icon="Search"
              clearable
              class="search-input"
            />
          </div>
          
          <!-- 通知 -->
          <el-badge :value="3" :hidden="false" class="notification-badge">
            <el-button text class="header-btn">
              <el-icon :size="18"><Bell /></el-icon>
            </el-button>
          </el-badge>
          
          <!-- 用户菜单 -->
          <el-dropdown @command="handleCommand" class="user-dropdown">
            <div class="user-trigger">
              <el-avatar
                :src="userStore.userInfo.avatar"
                :size="32"
                class="user-avatar"
              >
                {{ userStore.userInfo.username?.charAt(0)?.toUpperCase() }}
              </el-avatar>
            </div>
            <template #dropdown>
              <el-dropdown-menu class="user-menu">
                <div class="user-info-header">
                  <div class="user-name">{{ userStore.userInfo.realName || userStore.userInfo.username }}</div>
                  <div class="user-email">admin@example.com</div>
                </div>
                <el-dropdown-item command="profile">
                  <el-icon><UserFilled /></el-icon>
                  个人资料
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>
                  设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>
      
      <!-- 标签页 -->
      <div class="tabs-container" v-if="tabsStore.tabs.length > 0">
        <div class="tabs-wrapper">
          <div class="tabs-nav">
            <div 
              v-for="tab in tabsStore.tabs" 
              :key="tab.name"
              class="tab-item"
              :class="{ active: tab.name === tabsStore.activeTab }"
              @click="handleTabClick({ paneName: tab.name })"
            >
              <span class="tab-label">{{ tab.title }}</span>
              <el-button 
                v-if="tab.closable !== false"
                text 
                class="tab-close"
                @click.stop="tabsStore.removeTab(tab.name)"
              >
                <el-icon :size="12"><Close /></el-icon>
              </el-button>
            </div>
          </div>
          
          <!-- 标签页操作 -->
          <div class="tabs-actions">
            <el-dropdown @command="handleTabsCommand" trigger="click">
              <el-button text class="tabs-action-btn">
                <el-icon :size="14"><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="closeOthers">关闭其他</el-dropdown-item>
                  <el-dropdown-item command="closeAll">关闭所有</el-dropdown-item>
                  <el-dropdown-item command="refresh">刷新页面</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      
      <!-- 页面内容 -->
      <main class="page-container">
        <div class="page-content">
          <transition name="fade" mode="out-in">
            <router-view />
          </transition>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useTabsStore } from '@/stores/tabs'
import { useMenuStore } from '@/stores/menu'
import { getIconComponent } from '@/utils/iconMap'
import DynamicMenu from '@/components/DynamicMenu.vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import {
  Menu, Search, Bell, MoreFilled, Setting, UserFilled, 
  SwitchButton, Fold, Expand, Close
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const tabsStore = useTabsStore()
const menuStore = useMenuStore()

// 基础状态
const searchKeyword = ref('')
const showBreadcrumb = computed(() => route.path !== '/admin/dashboard')

// 动态菜单数据
const menuRoutes = computed(() => {
  return menuStore.menuTree || []
})

// 侧边栏折叠状态同步
const sidebarCollapsedState = computed({
  get: () => menuStore.collapsed,
  set: (value) => {
    menuStore.collapsed = value
  }
})

// 切换侧边栏
const toggleSidebar = () => {
  menuStore.toggleCollapsed()
}

// 获取当前菜单代码（用于高亮当前菜单项）
const getCurrentMenuCode = () => {
  const currentPath = route.path
  const findMenuCode = (menus) => {
    for (const menu of menus) {
      // 比较时需要添加 /admin 前缀
      const fullMenuPath = `/admin${menu.path}`
      if (fullMenuPath === currentPath) {
        return menu.code
      }
      if (menu.children && menu.children.length > 0) {
        const found = findMenuCode(menu.children)
        if (found) return found
      }
    }
    return null
  }
  return findMenuCode(menuRoutes.value) || ''
}

// 处理动态菜单点击
const handleMenuClick = (menu) => {
  if (menu.path && menu.type === 1) { // 只有菜单类型才能跳转
    // 构建完整的路径（添加 /admin 前缀）
    const fullPath = `/admin${menu.path}`
    
    // 添加到标签页
    tabsStore.addTab({
      name: menu.code,
      title: menu.name,
      path: fullPath
    })
    
    // 跳转路由
    router.push(fullPath)
  }
}

// 处理标签页点击
const handleTabClick = (tab) => {
  const targetTab = tabsStore.tabs.find(t => t.name === tab.paneName)
  if (targetTab) {
    tabsStore.setActiveTab(targetTab.name)
    router.push(targetTab.path)
  }
}

// 处理标签页操作命令
const handleTabsCommand = (command) => {
  switch (command) {
    case 'closeOthers':
      tabsStore.closeOtherTabs(tabsStore.activeTab)
      break
    case 'closeAll':
      tabsStore.closeAllTabs()
      router.push('/admin/dashboard')
      break
    case 'refresh':
      window.location.reload()
      break
  }
}

// 处理用户下拉菜单
const handleCommand = async (command) => {
  switch (command) {
    case 'profile':
      tabsStore.addTab({
        name: 'profile',
        title: '个人中心',
        path: '/admin/profile'
      })
      router.push('/admin/profile')
      break
    case 'settings':
      tabsStore.addTab({
        name: 'settings',
        title: '设置',
        path: '/admin/settings'
      })
      router.push('/admin/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await userStore.logout()
        ElMessage.success('已退出登录')
        router.push('/login')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('退出登录失败:', error)
          ElMessage.error('退出登录失败，请稍后重试')
        }
      }
      break
  }
}

// 监听路由变化，同步标签页状态
watch(
  () => route.path,
  (newPath) => {
    // 根据当前路径找到对应的菜单项
    const findMenuByPath = (menus, path) => {
      for (const menu of menus) {
        // 构建完整的菜单路径进行比较
        const fullMenuPath = `/admin${menu.path}`
        if (fullMenuPath === path) {
          return menu
        }
        if (menu.children && menu.children.length > 0) {
          const found = findMenuByPath(menu.children, path)
          if (found) return found
        }
      }
      return null
    }
    
    const currentMenu = findMenuByPath(menuRoutes.value, newPath)
    if (currentMenu) {
      // 确保标签页存在
      const existingTab = tabsStore.tabs.find(t => t.name === currentMenu.code)
      if (!existingTab) {
        tabsStore.addTab({
          name: currentMenu.code,
          title: currentMenu.name,
          path: `/admin${currentMenu.path}`
        })
      }
      // 设置为活动标签页
      tabsStore.setActiveTab(currentMenu.code)
    }
  },
  { immediate: true }
)

// 组件挂载时初始化
onMounted(async () => {
  // 如果菜单数据为空，尝试重新获取
  if (menuStore.menuTree.length === 0 && userStore.isLoggedIn) {
    await menuStore.getCurrentUserMenu()
  }
})
</script>

<style scoped>
/* shadcn风格的设计系统 */
.admin-layout {
  height: 100vh;
  display: flex;
  background: hsl(0 0% 98%);
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 侧边栏 */
.sidebar {
  width: 256px;
  background: hsl(0 0% 100%);
  border-right: 1px solid hsl(214.3 31.8% 91.4%);
  display: flex;
  flex-direction: column;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 40;
}

.sidebar.collapsed {
  width: 64px;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid hsl(214.3 31.8% 91.4%);
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  width: 32px;
  height: 32px;
  background: hsl(221.2 83.2% 53.3%);
  color: white;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  color: hsl(222.2 84% 4.9%);
}

.sidebar-nav {
  flex: 1;
  padding: 16px 12px;
  overflow-y: auto;
}

.nav-menu {
  border: none !important;
  background: transparent !important;
}

.nav-menu :deep(.el-menu-item),
.nav-menu :deep(.el-sub-menu__title) {
  height: 40px;
  line-height: 40px;
  margin: 2px 0;
  border-radius: 6px;
  border: none !important;
  color: hsl(215.4 16.3% 46.9%) !important;
  font-weight: 500;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.nav-menu :deep(.el-menu-item:hover),
.nav-menu :deep(.el-sub-menu__title:hover) {
  background: hsl(210 40% 96%) !important;
  color: hsl(222.2 84% 4.9%) !important;
}

.nav-menu :deep(.el-menu-item.is-active) {
  background: hsl(221.2 83.2% 53.3%) !important;
  color: hsl(210 40% 98%) !important;
  font-weight: 600;
}

.nav-menu :deep(.el-sub-menu .el-menu-item) {
  margin: 1px 0;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  padding-left: 44px !important;
}

.nav-menu :deep(.el-menu-item .el-icon),
.nav-menu :deep(.el-sub-menu__title .el-icon) {
  margin-right: 12px;
  font-size: 16px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部导航栏 */
.header {
  height: 64px;
  background: hsl(0 0% 100%);
  border-bottom: 1px solid hsl(214.3 31.8% 91.4%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  z-index: 30;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sidebar-toggle {
  color: hsl(215.4 16.3% 46.9%) !important;
  background: transparent !important;
  border: 1px solid hsl(214.3 31.8% 91.4%) !important;
  border-radius: 6px !important;
  width: 40px;
  height: 40px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.sidebar-toggle:hover {
  background: hsl(210 40% 96%) !important;
  border-color: hsl(214.3 31.8% 91.4%) !important;
  color: hsl(222.2 84% 4.9%) !important;
}

.breadcrumb-nav {
  color: hsl(215.4 16.3% 46.9%);
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-box {
  width: 300px;
}

.search-input :deep(.el-input__wrapper) {
  background: hsl(210 40% 96%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 6px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: hsl(215.4 16.3% 46.9%);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: hsl(221.2 83.2% 53.3%);
  box-shadow: 0 0 0 2px hsl(221.2 83.2% 53.3% / 0.2);
}

.header-btn {
  color: hsl(215.4 16.3% 46.9%) !important;
  background: transparent !important;
  border: 1px solid hsl(214.3 31.8% 91.4%) !important;
  border-radius: 6px !important;
  width: 40px;
  height: 40px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.header-btn:hover {
  background: hsl(210 40% 96%) !important;
  color: hsl(222.2 84% 4.9%) !important;
}

.notification-badge {
  margin-right: 8px;
}

.user-trigger {
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.user-trigger:hover {
  background: hsl(210 40% 96%);
}

.user-avatar {
  border: 2px solid hsl(214.3 31.8% 91.4%);
}

.user-menu {
  min-width: 200px;
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 8px;
  box-shadow: 0 4px 6px -1px hsl(220 43% 11% / 0.1);
}

.user-info-header {
  padding: 12px 16px;
  border-bottom: 1px solid hsl(214.3 31.8% 91.4%);
}

.user-name {
  font-weight: 600;
  color: hsl(222.2 84% 4.9%);
  font-size: 14px;
}

.user-email {
  color: hsl(215.4 16.3% 46.9%);
  font-size: 12px;
  margin-top: 2px;
}

/* 标签页 - 重新设计 */
.tabs-container {
  background: hsl(0 0% 100%);
  border-bottom: 1px solid hsl(214.3 31.8% 91.4%);
  min-height: 48px;
}

.tabs-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 48px;
}

.tabs-nav {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.tabs-nav::-webkit-scrollbar {
  display: none;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: hsl(210 40% 96%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  white-space: nowrap;
  font-size: 13px;
  font-weight: 500;
  color: hsl(215.4 16.3% 46.9%);
  min-width: 0;
  flex-shrink: 0;
}

.tab-item:hover {
  background: hsl(0 0% 100%);
  color: hsl(222.2 84% 4.9%);
  border-color: hsl(215.4 16.3% 46.9%);
}

.tab-item.active {
  background: hsl(221.2 83.2% 53.3%);
  color: hsl(210 40% 98%);
  border-color: hsl(221.2 83.2% 53.3%);
  font-weight: 600;
}

.tab-label {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tab-close {
  color: inherit !important;
  background: transparent !important;
  border: none !important;
  padding: 2px !important;
  width: 16px !important;
  height: 16px !important;
  border-radius: 3px !important;
  opacity: 0.7;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  flex-shrink: 0;
}

.tab-close:hover {
  opacity: 1;
  background: rgba(0, 0, 0, 0.1) !important;
}

.tab-item.active .tab-close:hover {
  background: rgba(255, 255, 255, 0.2) !important;
}

.tabs-actions {
  display: flex;
  align-items: center;
  margin-left: 12px;
}

.tabs-action-btn {
  color: hsl(215.4 16.3% 46.9%) !important;
  background: transparent !important;
  border: 1px solid hsl(214.3 31.8% 91.4%) !important;
  border-radius: 6px !important;
  width: 28px !important;
  height: 28px !important;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 0 !important;
}

.tabs-action-btn:hover {
  background: hsl(210 40% 96%) !important;
  color: hsl(222.2 84% 4.9%) !important;
  border-color: hsl(215.4 16.3% 46.9%) !important;
}

/* 页面容器 */
.page-container {
  flex: 1;
  overflow: hidden;
  background: hsl(0 0% 98%);
}

.page-content {
  height: 100%;
  overflow-y: auto;
  padding: 24px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    z-index: 50;
    transform: translateX(-100%);
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
  
  .sidebar:not(.collapsed) {
    transform: translateX(0);
  }
  
  .main-content {
    margin-left: 0;
  }
  
  .search-box {
    display: none;
  }
  
  .header {
    padding: 0 16px;
  }
}

/* 滚动条样式 */
.sidebar-nav::-webkit-scrollbar,
.page-content::-webkit-scrollbar {
  width: 6px;
}

.sidebar-nav::-webkit-scrollbar-track,
.page-content::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar-nav::-webkit-scrollbar-thumb,
.page-content::-webkit-scrollbar-thumb {
  background: hsl(215.4 16.3% 46.9% / 0.3);
  border-radius: 3px;
}

.sidebar-nav::-webkit-scrollbar-thumb:hover,
.page-content::-webkit-scrollbar-thumb:hover {
  background: hsl(215.4 16.3% 46.9% / 0.5);
}
</style>